<!--
  * 物料信息
  *
  * @Author:    lmabbe
  * @Date:      2025-06-24 17:04:42
  * @Copyright  lmabbe
-->
<template>
  <a-modal
    :destroyOnClose="true"
    :maskClosable="false"
    :open="visibleFlag"
    :title="form.materialCode ? '编辑' : '添加'"
    :width="900"
    @close="onClose"
  >
    <a-form ref="formRef" :label-col="{ style: 'width: 100px; display: inline-block; vertical-align: inherit;' }" :model="form" :rules="rules">
      <a-row>
        <a-col :span="12">
          <a-form-item label="物料编码" name="materialCode">
            <a-input v-model:value="form.materialCode" :disabled="!state.addFlag" placeholder="物料编码" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="旧物料编码" name="oldMaterialCode">
            <a-input v-model:value="form.oldMaterialCode" placeholder="旧物料编码" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="物料名称" name="materialName">
            <a-input v-model:value="form.materialName" placeholder="物料名称" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="物料规格" name="materialSpec">
            <a-input v-model:value="form.materialSpec" placeholder="物料规格" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="物料描述" name="materialDesc">
            <a-input v-model:value="form.materialDesc" placeholder="物料描述" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="物料属性" name="materialProperty">
            <DictSelect v-model:value="form.materialProperty" dict-code="MATERIAL_PROPERTY" placeholder="物料属性" width="100%" />
          </a-form-item>
        </a-col>
        <a-col v-if="form.materialProperty === 'EXCIPIENTS'" :span="8">
          <a-form-item label="辅料类型" name="excipientsType">
            <DictSelect v-model:value="form.excipientsType" dict-code="MATERIAL_EXCIPIENTS_TYPE" placeholder="辅料类型" width="100%" />
          </a-form-item>
        </a-col>
        <a-col v-if="form.materialProperty === 'ROW'" :span="8">
          <a-form-item label="物料类型" name="materialType">
            <DictSelect v-model:value="form.materialType" dict-code="MATERIAL_TYPE" placeholder="物料类型" width="100%" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="归属客户" name="belongCustomer">
            <a-select v-model:value="form.belongCustomer" :allowClear="true" :style="`width: 100%`" placeholder="请选择归属客户">
              <a-select-option v-for="item in state.customerData" :key="item.customerCode" :value="item.customerCode">
                {{ item.customerAbbreviation }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="物料单位" name="materialUnit">
            <DictSelect v-model:value="form.materialUnit" dict-code="MATERIAL_UNIT" placeholder="物料单位" width="100%" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="有效天数" name="validDays">
            <a-input-number v-model:value="form.validDays" :min="1" placeholder="有效天数" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="默认存储储位" name="defaultStorageLocation">
            <a-input v-model:value="form.defaultStorageLocation" placeholder="默认存储储位" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="损耗率(百分比)" name="lossRate">
            <a-input-number v-model:value="form.lossRate" :min="0" :step="0.001" placeholder="损耗率(百分比)" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="归属供应商" name="belongSupplierInfo">
            <a-select v-model:value="form.belongSupplierInfo" :allowClear="true" :style="`width: 100%`" placeholder="请选择归属供应商">
              <a-select-option v-for="item in state.supplierData" :key="item.supplierCode" :value="item.supplierAbbreviation">
                {{ item.supplierAbbreviation }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
        <a-button v-if="state.addFlag" type="primary" @click="onSubmitNext">保存并继续添加</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { materialInfoApi } from '/@/api/business/basic/material/material-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js';
  import { supplierInfoApi } from '/@/api/business/basic/supplier/supplier-info-api.js';
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  const state = reactive({
    customerData: [],
    supplierData: [],
    addFlag: false,
  });

  function show(rowData, addFlag) {
    Object.assign(form, formDefault);
    state.addFlag = addFlag;
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
    customerAll();
    supplierAll();
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  function customerAll() {
    customerInfoApi.customerAll().then((res) => {
      state.customerData = res.data;
    });
  }

  function supplierAll() {
    supplierInfoApi.all().then((res) => {
      state.supplierData = res.data;
    });
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    materialCode: undefined, //物料编码
    materialName: undefined, //物料名称
    materialSpec: undefined, //物料规格
    materialDesc: undefined, //物料描述
    materialType: undefined, //物料类型
    excipientsType: undefined, //辅料类型
    belongCustomer: undefined, //归属客户
    oldMaterialCode: undefined, //旧物料编码
    materialUnit: undefined, //物料单位
    validDays: 365, //有效天数
    defaultStorageLocation: undefined, //默认存储储位
    lossRate: 0.005, //损耗率(百分比)
    belongSupplierInfo: undefined, //归属供应商
    materialProperty: undefined, //物料属性
  };

  let form = reactive({ ...formDefault });

  const rules = {
    materialCode: [{ required: true, message: '物料编码 必填' }],
    materialName: [{ required: true, message: '物料名称 必填' }],
    materialSpec: [{ required: true, message: '物料规格 必填' }],
    materialDesc: [{ required: true, message: '物料描述 必填' }],
    materialType: [{ required: true, message: '物料类型 必填' }],
    belongCustomer: [{ required: true, message: '归属客户 必填' }],
    materialUnit: [{ required: true, message: '物料单位 必填' }],
    validDays: [{ required: true, message: '有效天数 必填' }],
    materialProperty: [{ required: true, message: '物料属性 必填' }],
    excipientsType: [{ required: true, message: '辅料类型 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
      onClose();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  async function onSubmitNext() {
    try {
      await formRef.value.validateFields();
      save();
      form.materialCode = '';
      form.oldMaterialCode = '';
      form.materialName = '';
      form.materialDesc = '';
      form.materialSpec = '';
      form.defaultStorageLocation = '';
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (!state.addFlag) {
        await materialInfoApi.update(form);
      } else {
        await materialInfoApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,
  });
</script>
